cmake_minimum_required(VERSION 3.5)
project(libfunchook_test LANGUAGES C CXX ASM)

set(FUNCHOOK_CPU ${CMAKE_SYSTEM_PROCESSOR})

if (FUNCHOOK_CPU STREQUAL AMD64)
  set(FUNCHOOK_CPU "x86_64")
endif ()

if (FUNCHOOK_CPU STREQUAL x86_64)
  if (CMAKE_SIZEOF_VOID_P EQUAL "4")
    set(FUNCHOOK_CPU "x86")
  endif ()
endif ()

if (FUNCHOOK_CPU MATCHES "i.86")
  set(FUNCHOOK_CPU "x86")
endif ()

if (FUNCHOOK_CPU STREQUAL "arm64")
  set(FUNCHOOK_CPU "aarch64")
endif ()

set(TEST_EXE_SOURCES test_main.c test_prehook.c test_cpp.cpp unit_test.c)
if (FUNCHOOK_CPU STREQUAL x86)
  set(TEST_EXE_SOURCES ${TEST_EXE_SOURCES} ${FUNCHOOK_CPU}_test.S)
endif ()


if (NOT MSVC)
  set(FUNCHOOK_ASM_SUFFIX _gas.S)
elseif (FUNCHOOK_CPU MATCHES "^x86")
  enable_language(ASM_MASM)
  set(FUNCHOOK_ASM_SUFFIX _masm.asm)
else ()
  set(FUNCHOOK_CPU noasm)
  set(FUNCHOOK_ASM_SUFFIX .c)
endif ()

add_library(funchook_test SHARED libfunchook_test.c libfunchook_test_cpp.cpp libfunchook_test_${FUNCHOOK_CPU}${FUNCHOOK_ASM_SUFFIX})
target_compile_definitions(funchook_test PRIVATE FUNCHOOK_TEST_EXPORTS)
if (MSVC)
  set_target_properties(funchook_test PROPERTIES OUTPUT_NAME funchook_test_dll)
  if (CMAKE_SIZEOF_VOID_P MATCHES "4")
    set_source_files_properties(libfunchook_test_x86_masm.asm PROPERTIES COMPILE_FLAGS /safeseh)
  endif ()
else ()
  set_target_properties(funchook_test PROPERTIES SUFFIX ".so")
endif ()

set(FUNCHOOK_TEST_LIBS funchook_test)
if (UNIX)
  set(FUNCHOOK_TEST_LIBS ${FUNCHOOK_TEST_LIBS} dl)
endif ()

set(CMD "")
if (CMAKE_HOST_UNIX AND MINGW)
  find_program(WINE_EXECUTABLE NAMES wine)
  set(CMD ${WINE_EXECUTABLE})
endif ()

if (FUNCHOOK_BUILD_SHARED)
  add_executable(funchook_test_shared ${TEST_EXE_SOURCES})
  target_link_libraries(funchook_test_shared PRIVATE funchook-shared ${FUNCHOOK_TEST_LIBS})
  if (UNIX)
    set_target_properties(funchook_test_shared PROPERTIES LINK_FLAGS -rdynamic)
  endif ()
  if (WIN32)
    add_custom_command(TARGET funchook_test_shared POST_BUILD COMMAND ${CMAKE_COMMAND} -E copy $<TARGET_FILE:funchook-shared> $<TARGET_FILE_DIR:funchook_test_shared>)
  endif ()
  if (CMAKE_COMPILER_IS_GNUCC OR CMAKE_COMPILER_IS_GNUCXX)
    target_compile_options(funchook_test_shared PRIVATE -Wall -Wextra -Werror)
  endif ()
  add_test(NAME funchook_test_shared COMMAND ${CMD} $<TARGET_FILE:funchook_test_shared>)
endif ()

if (FUNCHOOK_BUILD_STATIC)
  add_executable(funchook_test_static ${TEST_EXE_SOURCES})
  target_link_libraries(funchook_test_static PRIVATE funchook-static ${FUNCHOOK_TEST_LIBS})
  if (UNIX)
    set_target_properties(funchook_test_static PROPERTIES LINK_FLAGS -rdynamic)
  endif ()
  if (CMAKE_COMPILER_IS_GNUCC OR CMAKE_COMPILER_IS_GNUCXX)
    target_compile_options(funchook_test_static PRIVATE -Wall -Wextra -Werror)
  endif ()
  add_test(NAME funchook_test_static COMMAND ${CMD} $<TARGET_FILE:funchook_test_static>)
endif ()
